//
//  BKExchangeVoucherViewController.m
//  bestkeep
//
//  Created by yons on 16/12/5.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKExchangeVoucherViewController.h"
#import "BKExchangeVoucherCell.h"
#import "BK_EXChangeVoucher_Bottom_View.h"
#import "BKIntegralBookViewController.h"
#import "BKMainCommon.h"
#import "BKCouponInfoModel.h"
#import "BK_OD_Color.h"
#import "BKEXVoucherDetailCell.h"
#import "Ex_Vouncher_Footer.h"
@interface UIScrollView(BKExchangeFooterView)

@property(nonatomic,strong) UIView *BKExchange_footerView;

@end

@implementation UIScrollView(BKExchangeFooterView)

static char const BKExchange_footerViewKey = '\0';

-(void)setBKExchange_footerView:(UIView *)BKExchange_footerView {
    objc_setAssociatedObject(self, &BKExchange_footerViewKey, BKExchange_footerView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    if(BKExchange_footerView) {
        
        CGRect frame = BKExchange_footerView.frame;
        frame.origin.y = self.contentSize.height;
        
        CGFloat contentHeight = self.contentSize.height;
        if(contentHeight + CGRectGetHeight(frame) < CGRectGetHeight([[UIScreen mainScreen] bounds]) - 64 - 49) {
            CGFloat y = CGRectGetHeight([[UIScreen mainScreen] bounds]) - 64 - 49 - contentHeight - CGRectGetHeight(BKExchange_footerView.frame);
            frame.origin.y += y;
        }
        
        
        BKExchange_footerView.frame = frame;
        
        self.contentInset = UIEdgeInsetsMake(0, 0, CGRectGetHeight(BKExchange_footerView.frame), 0);
        
        [self addSubview:BKExchange_footerView];
        
    } else {
        self.contentInset = UIEdgeInsetsZero;
    }
}

-(UIView *)BKExchange_footerView {
    return objc_getAssociatedObject(self, &BKExchange_footerViewKey);
}

@end


@interface BKExchangeVoucherViewController ()<UITableViewDelegate,UITableViewDataSource,BKBottomViewDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)BKCouponInfoModel *model;
@property(nonatomic,strong)BK_EXChangeVoucher_Bottom_View *bottomView_EXChangeVoucher;
@property(nonatomic,strong)ExceptionView *exceptionView;
@property(nonatomic,strong)NSMutableArray * marr_Section;

@end

@implementation BKExchangeVoucherViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self  setProperty];
    [self  check_NetWork];
    
}


#pragma mark==================setProperty======================
-(void)setProperty{
    
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    self.title = @"兑换优惠券";
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
}


#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            [self BK_getData_ExchangeVoucher];
            
        }
            break;
            
        default: {
            [HUD dismiss];
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
            break;
    }
}

#pragma mark  ---------- 数据请求 -----------------
-(void)BK_getData_ExchangeVoucher{
    [LoadingView loadingShoppingCartInView:self.view];
    [BKIntegralCommon getcouponInfo:self.couponId callback:^(BOOL isSucess, id obj, NSError *error) {
        if (isSucess) {
            self.model = [[BKCouponInfoModel alloc] initWithDictionary:obj];
            [self Create_marr_Section];
            [self updateView];
        }
        [LoadingView dismiss];
    }];
}




#pragma mark ------数据请求成功后加载页面-----
-(void)updateView{
    
    _bottomView_EXChangeVoucher = [[BK_EXChangeVoucher_Bottom_View alloc]init];
    _bottomView_EXChangeVoucher.deleaget  = self;
    [self.view addSubview:_bottomView_EXChangeVoucher];
    [_bottomView_EXChangeVoucher mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.bottom.mas_equalTo(self.view.mas_bottom);
        make.height.mas_equalTo(49);
    }];
    [self.bottomView_EXChangeVoucher UpdateBottomView:self.model];
    
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView registerClass:[BKExchangeVoucherCell class] forCellReuseIdentifier:NSStringFromClass([BKExchangeVoucherCell class])];
    [_tableView registerClass:[BKEXVoucherDetailCell class] forCellReuseIdentifier:NSStringFromClass([BKEXVoucherDetailCell class])];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.right.mas_equalTo(self.view.mas_right);
        make.top.mas_equalTo(self.view.mas_top);
        make.bottom.mas_equalTo(self.bottomView_EXChangeVoucher.mas_top);
    }];
    [_tableView reloadData];

    _tableView.BKExchange_footerView = [Ex_Vouncher_Footer get_Ex_Vouncher_Footer];

}
#pragma mark ----------tableView Delegate------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.footerHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    return cm.height;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    
    cell.selectionStyle = cm.selectionStyle;

    if ([cm.className isEqualToString:NSStringFromClass([BKExchangeVoucherCell class])]) {
        BKExchangeVoucherCell *ex_cell=(BKExchangeVoucherCell *)cell;
        ex_cell.titleLabel.text = self.model.coupon_amount_text;
        ex_cell.useType.text = self.model.userRange;
        NSString *string = [NSString stringWithFormat:@"¥%@", self.model.coupon_amount];
        if (string != nil) {
            NSMutableAttributedString *attri = [[NSMutableAttributedString alloc]initWithString:string];
            [attri addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:18] range:NSMakeRange(0, 1)];
            [attri addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:32] range:NSMakeRange(1, string.length - 1)];
            ex_cell.moneyLabel.attributedText = attri;
        }
    }else if([cm.className isEqualToString:NSStringFromClass([BKEXVoucherDetailCell class])]){

        BKEXVoucherDetailCell *ex_cell=(BKEXVoucherDetailCell *)cell;
        [ex_cell setdataWithModel:self.model];

    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
#pragma mark ---------bottomViewDelegate------------------
//赚取积分
-(void)makeScoresButtonAction:(UIButton *)sender{
    BKIntegralBookViewController *integralBookVC = [[BKIntegralBookViewController alloc]init];
    integralBookVC.urlString = @"http://cdn.bestkeep.cn/ui/mobile/html/Integral.html";
    integralBookVC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:integralBookVC animated:YES];
}
//积分不够用
- (void)scoresUnenoughButtonAction:(UIButton *)sender {
    
}
//兑换积分
-(void)exchangeScoresButtonAction:(UIButton *)sender{
    UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"确认兑换此优惠券" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alart show];
    
}
#pragma mark ---------UIAlertViewDelegate----------
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {
        case 0:
            
            break;
            
        case 1:
            
//            [self exchangeVouncher];
            
            break;
            
        default:
            break;
    }
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            
            break;
            
        case 1:
            
             [self exchangeVouncher];
            
            break;
            
        default:
            break;
    }
}
-(void)exchangeVouncher{
    [BKIntegralCommon exchangeCoupon:self.couponId mycallBack:^(BOOL isSucess, id obj, NSError *error) {
        if (isSucess) {

            [HUD showSuccessMessage:@"兑换成功"];
            [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(wait) userInfo:nil repeats:NO];

        }else{
            NSLog(@"%@",obj[@"msg"]);
        }
    }];
}

-(void)wait{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

-(void)Create_marr_Section{
    
        _marr_Section=[[NSMutableArray alloc]init];
        NSMutableArray *Cells = [NSMutableArray array];
        
            CellModel *cell0 = [[CellModel alloc] init];
            cell0.className = NSStringFromClass([BKExchangeVoucherCell class]);
            cell0.reuseIdentifier = NSStringFromClass([BKExchangeVoucherCell class]);
            cell0.height = 125;
            cell0.selectionStyle = UITableViewCellSelectionStyleNone;
            //            gc.userInfo = goods;
            [Cells addObject:cell0];
        
        
            CellModel *cell1 = [[CellModel alloc] init];
            cell1.className = NSStringFromClass([BKEXVoucherDetailCell class]);
            cell1.reuseIdentifier = NSStringFromClass([BKEXVoucherDetailCell class]);
            cell1.height = [BKEXVoucherDetailCell getCellHeightWithModel:self.model];
            cell1.selectionStyle = UITableViewCellSelectionStyleNone;
            //            gc.userInfo = goods;
            [Cells addObject:cell1];


        SectionModel *Section0 = [SectionModel sectionModelWithTitle:nil cells:Cells.copy];
        Section0.headerhHeight = 0.00001;
        Section0.footerHeight  = 0.00001;
        
        [_marr_Section addObject:Section0];
    
    
}


- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];

}


@end































